package promotion

import (
	// "bp/cache"
	"bp/conf"
	"bp/db"

	// "bgs/grpc/client"
	internalHttpMiddleware "bp/internal/middleware/http"
	"bp/internal/service/entity"
	"bp/internal/twirpex"
	"go.uber.org/zap"

	// "bp/internal/util"
	messageGrpc "bp/rpc/gen/shared/message"
	promotionGrpc "bp/rpc/gen/webapi/promotion"
	"context"

	"github.com/go-chi/chi"
	"github.com/golang/protobuf/ptypes/empty"
)

type PromotionWebApiImp struct {
	dao       *db.PgDao
	slog      *zap.SugaredLogger
	vars      *conf.VarsSection
	entityHub *entity.EntityHub
	// cacher *cache.Adapter
	promotionGrpc.PromotionOpService
}

// NewPromotionWebApi initialization
func NewPromotionWebApi(
	slog *zap.SugaredLogger,
	pgdao *db.PgDao,
	vars *conf.VarsSection,
	entityHub *entity.EntityHub,
	// adp *cache.Adapter,
) (ws *PromotionWebApiImp) {
	ws = &PromotionWebApiImp{
		dao:       pgdao,
		slog:      slog.With("module", "PromotionWebApi"),
		vars:      vars,
		entityHub: entityHub,
		// cacher:           adp,
	}
	return
}

const (
	EntityName                   string = "促销活动"
	PingPromotionMethod          string = "/promotion/ping/exec"
	CreatePromotionMethod        string = "/promotion"              // POST
	UpdatePromotionMethod        string = "/promotion"              // PUT
	PublishPromotionMethod       string = "/promotion/{id}/publish" // PUT
	PausePromotionMethod         string = "/promotion/{id}/pause"   // PUT
	ResumePromotionMethod        string = "/promotion/{id}/resume"  // PUT
	GetPromotionMethod           string = "/promotion/{id}"         // GET
	ListPromotionsMethod         string = "/promotions"             // GET
	ListPromotionWithStatsMethod string = "/promotionWithStats"     // GET
)

// RegisterToWeb 将部分grpc方法注册到web
func (s *PromotionWebApiImp) RegisterToWeb(r chi.Router) {
	promotionRT := twirpex.NewSingleTwirpServerProxy(promotionGrpc.NewPromotionOpServiceServer(s))

	r.Group(func(r chi.Router) {
		r.Get(PingPromotionMethod, promotionRT.Handle("PingPromotion"))
		r.Group(func(r chi.Router) {
			r.Use(internalHttpMiddleware.WithBilinToken(s.slog, s.vars))
			r.Post(CreatePromotionMethod, promotionRT.Handle("CreatePromotion"))
			r.Put(UpdatePromotionMethod, promotionRT.Handle("UpdatePromotion"))
			r.Put(PublishPromotionMethod, promotionRT.Handle("PublishPromotion"))
			r.Put(PausePromotionMethod, promotionRT.Handle("PausePromotion"))
			r.Put(ResumePromotionMethod, promotionRT.Handle("ResumePromotion"))
			r.Get(GetPromotionMethod, promotionRT.Handle("GetPromotion"))
			r.Group(func(r chi.Router) {
				r.Use(internalHttpMiddleware.WithPager(s.slog, s.vars))
				r.Get(ListPromotionsMethod, promotionRT.Handle("ListPromotions"))
				r.Get(ListPromotionWithStatsMethod, promotionRT.Handle("ListPromotionWithStats"))
			})
		})
	})
}

func (s *PromotionWebApiImp) PingPromotion(ctx context.Context, _ *empty.Empty) (res *messageGrpc.PingRes, err error) {
	res = &messageGrpc.PingRes{
		Msg: "ok",
	}
	return
}
